package com.sandy.springdata

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

import java.text.DateFormat
import java.text.SimpleDateFormat

@RestController
@RequestMapping(value = "/student")
class StudentController {

    @Autowired
    StudentRepository stdRepo

    @GetMapping('/add')
    Student add() {
        def std = new Student(
                name: 'sandy',
                studentNo: '1234567890',
                birthday: new SimpleDateFormat('yyyy-MM-dd').parse('1982-11-21'),
                sex: SexType.MALE,
        )
        stdRepo.save(std)
    }

    @GetMapping('/{studentNo}')
    Student get(@PathVariable String studentNo) {
        stdRepo.findFirstByStudentNo(studentNo)
    }

    @GetMapping('/{studentNo}/info')
    Map getInfo(@PathVariable String studentNo) {
        def std = stdRepo.findFirstByStudentNo(studentNo)
        [
                studentNo: std.studentNo,
                name     : std.name,
        ]
    }

    @GetMapping('/list')
    List<Student> list() {
        stdRepo.findAll()
    }

    @GetMapping('/names')
    List<String> listNames() {
        List<Student> students = stdRepo.findAll()
        students*.name
    }

    @GetMapping('/infoList')
    List<Map> infoList() {
        def students = stdRepo.findAll()
        students.collect {
            [
                    studentNo: it.studentNo,
                    name     : it.name,
            ]
        }
    }
}
